package com.example.yml0612;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatImageView;

public class CircleImage extends AppCompatImageView {
    private int radius;

    public CircleImage(Context context) {
        super(context);
    }

    public CircleImage(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CircleImage(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int min = Math.min(getMeasuredWidth(), getMeasuredHeight());
        radius = min / 2;

        setMeasuredDimension(min, min);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //画笔
        Paint paint = new Paint();
        //获取图片
        Drawable drawable = getDrawable();
        //将图片转为位图对象
        Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
        //着色器
        //
        BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.MIRROR, Shader.TileMode.CLAMP);
        //计算缩放比例
        float scale = (radius * 2.0f) / Math.min(bitmap.getHeight(), bitmap.getWidth());
        //制作一个矩阵,根本作用是为了做坐标的转换
        Matrix matrix = new Matrix();
        //设置矩阵的坐标的缩放比例
        matrix.setScale(scale, scale);
        //将矩阵设置给着色器
        bitmapShader.setLocalMatrix(matrix);
        //将着色器设置给画笔
        paint.setShader(bitmapShader);
        //画圆
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, radius, paint);
    }
}
